<!--
 * @Author: 曹捷
 * @Date: 2019-12-16 16:22:03
 * @LastEditors: 曹捷
 * @LastEditTime: 2019-12-16 18:25:27
 * @Description: 解析 富文本域  只要是为单独dom添加事件  小程序不支持dom 只能解析
 -->
<template>
  <div class="desc text-indent" id="desc">
    <p :key="index" v-for="(item,index) in list">
      <span :key="cindex" v-for="(citem,cindex) in item">
        <template v-if="citem.type ==='text'">{{citem.content}}</template>
        <template v-html="citem.content" v-if="citem.type ==='dom'"></template>
        <div @click="showImgDetails(citem)" class="text-row" v-if="citem.type ==='img'">
          <image :src="citem.content" class="showimg" mode="aspectFill" />
        </div>
      </span>
    </p>
  </div>
</template>

<script>
export default {
  props: {
    htmltext: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  watch: {
    htmltext() {
      this.toTranstrom()
    }
  },
  methods: {
    showImgDetails(item) {
      console.log('TCL: showImgDetails -> item', item)
      uni.previewImage({
        current: [0],
        urls: [item.content],
        success() {}
      })
    },
    toTranstrom() {
      let html = this.htmltext
      let list = html.split('</p>')
      let res = []
      list.forEach(element => {
        let urls = []
        element = element.replace('<p>', '')
        if (element.indexOf('img') !== -1) {
          toDom(element)
          function toDom(info) {
            //   解析里面含有换行或者图片标签
            if (info.indexOf('<') === -1) {
              //解析最后纯文本
              urls.push({
                type: 'text',
                content: info
              })
            } else if (info.indexOf('<img') > 0) {
              // 解析开头是文本
              urls.push({
                type: 'text',
                content: info.substring(0, info.indexOf('<img'))
              })
              info = info.substring(info.indexOf('<img'))
              if (info.length > 0) {
                toDom(info)
              }
            } else {
              // 解析开头就是图片
              var imgContent = info.substring(0, info.indexOf('>'))
              urls.push({
                type: 'img',
                content: imgContent.substring(
                  imgContent.indexOf('src=') + 5,
                  imgContent.lastIndexOf('"')
                )
              })
              info = info.substring(info.indexOf('>') + 1)
              if (info.length > 0) {
                toDom(info)
              }
            }
          }
        } else if (element.indexOf('<') !== -1) {
          urls.push({
            type: 'dom',
            content: element
          })
        } else {
          urls.push({
            type: 'text',
            content: element
          })
        }
        res.push(urls)
      })
      this.list = res
    }
  },
  mounted() {
    this.toTranstrom()
  }
}
</script>

<style>
</style>